package com.itheima.factory;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author wz
 * @description:
 * @date 2021-10-30
 */
public class BeanFactory {

    private static Map<String ,String> beanDefinationMap=new HashMap<String ,String>();

    private static Map<String,String> beanDefination=new HashMap<String,String>();

    //  使用静态代码块，实现bean.properties文件资源走io只加载一次即可
    static {
        //  加载配置文件
        ResourceBundle bundle = ResourceBundle.getBundle("bean");
        // 获取beanName对应的类全限定名
        Enumeration<String> keys = bundle.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String className=bundle.getString(key);
            beanDefination.put(key,className);
        }
    }

    //  获取bean对象
//    public static Object getBean(String beanName) throws Exception {
//        // 通过传入的beanName获取ClassName  反射创建对象
//        String className = beanDefination.get(beanName);
//        Class<?> aClass = Class.forName(className);
//        Object bean = aClass.newInstance();
//        return bean;
//    }
/**
    public static Object getBean(String beanName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //1.读取properties文件 底层走i/0
        ResourceBundle bundle = ResourceBundle.getBundle("bean");
        //2.循环获取beanName对应的类的全限定名称
        Enumeration<String> keys = bundle.getKeys();
        Object bean=null;
        while (keys.hasMoreElements()) {
            String className = keys.nextElement();
            if (className.equals(beanName)) {
                String cName = bundle.getString(beanName);
                //3.通过反射获取bean对象
                 bean = Class.forName(cName).newInstance();
            }
        }
        //4.返回
        return bean;
    }
 */

    /**
     * bean加载模式
     * @param beanName
     * @return
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static Object getBean(String beanName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //获取key获取value值
        Object bean=null;
        String cName = beanDefinationMap.get(beanName);
        if (cName!=null) {
            bean=Class.forName(cName).newInstance();
        }
        //4.返回
        return bean;
    }
}
